/*
 *    Copyright 2022 The DSMS Authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dsms.common.taskmanager;

import com.dsms.common.constant.TaskTypeEnum;
import com.dsms.common.taskmanager.model.Task;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

@Component
public class TaskContext {

    private static final String INVALID_TASK_TYPE = "Invalid task type";
    /**
     * Spring will automatically inject the implementation class of the TaskStrategy interface into this Map,
     * the key is the bean id and the value is the implementation class
     */
    private Map<String, TaskStrategy> dsmsStorageTaskMap;

    public TaskContext(Map<String, TaskStrategy> dsmsStorageTaskMap) {
        this.dsmsStorageTaskMap = dsmsStorageTaskMap;
    }

    /**
     * execute task strategy dependencies task type
     *
     * @param executeTask task
     * @return task with executed status
     */
    public Task execute(Task executeTask) {
        TaskStrategy taskStrategy = Optional.ofNullable(dsmsStorageTaskMap.get(executeTask.getTaskType()))
                                            .orElseThrow(() -> new IllegalArgumentException(INVALID_TASK_TYPE));
        return taskStrategy.execute(executeTask);
    }

    /**
     * some task should roll back when it failed
     *
     * @param rollbackTask task
     * @return task with rollback or rollback_success status
     */
    public Task rollback(Task rollbackTask) {
        TaskStrategy taskStrategy = Optional.ofNullable(dsmsStorageTaskMap.get(rollbackTask.getTaskType()))
                                            .orElseThrow(() -> new IllegalArgumentException(INVALID_TASK_TYPE));
        return taskStrategy.rollback(rollbackTask);
    }

    /**
     * validate task unique dependencies task type, different task has different validateParams
     *
     * @param taskTypeEnum task type enum
     * @param validateParam validate parameter
     * @return validate result
     */
    public boolean validateTask(TaskTypeEnum taskTypeEnum, String... validateParam) {
        TaskStrategy taskStrategy = Optional.ofNullable(dsmsStorageTaskMap.get(taskTypeEnum.getType()))
                                            .orElseThrow(() -> new IllegalArgumentException(INVALID_TASK_TYPE));
        return taskStrategy.validateTask(validateParam);
    }

}
